package com.douban.crawl.utils;


import com.douban.crawl.constants.Constants;
import org.jsoup.Connection;
import org.jsoup.Jsoup;

import java.io.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class CommonUtil {
    /**
     * 设置代理IP和端口
     */
    public static void setGlobalIPAndPort() {
        System.setProperty("http.maxRedirects", "50");
        System.getProperties().setProperty("proxySet", "true");
        // 如果不设置，只要代理IP和代理端口正确,此项不设置也可以
        System.getProperties().setProperty("http.proxyHost", Constants.IP);
        System.getProperties().setProperty("http.proxyPort", Constants.PORT);
    }

    /**
     * 提取字符串中的数字
     * @param str
     * @return
     */
    public static String extractNumber(String str) {
        String regEx="[^0-9]";
        Pattern p = Pattern.compile(regEx);
        Matcher m = p.matcher(str);
        return m.replaceAll("").trim();
    }

    public static void downloadImg(String imgUrl) {
        String basePath = "webapp/download/";
        try {
            String fileName = getFileName(imgUrl);
            // 如果存在就不进行下载了
            File originFile = new File(basePath + fileName);
            if (originFile.exists()) {
                return;
            }
            Connection connection = Jsoup.connect(imgUrl);
            Connection.Response response = connection.method(Connection.Method.GET).ignoreContentType(true).timeout(3*1000).execute();
            BufferedInputStream bufferedInputStream = response.bodyStream();
            saveFile(bufferedInputStream,basePath + fileName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private static void saveFile(BufferedInputStream bufferedInputStream,String savePath) throws IOException {
        //一次最多读取1k
        byte[] buffer = new byte[1024];
        //实际读取的长度
        int readLenghth;
        //根据文件保存地址，创建文件输出流
        FileOutputStream fileOutputStream = new FileOutputStream(new File(savePath));
        //创建的一个写出的缓冲流
        BufferedOutputStream bufferedOutputStream = new BufferedOutputStream(fileOutputStream);
        //文件逐步写入本地
        while ((readLenghth = bufferedInputStream.read(buffer,0,1024)) != -1){//先读出来，保存在buffer数组中
            bufferedOutputStream.write(buffer,0,readLenghth);//再从buffer中取出来保存到本地
        }
        //关闭缓冲流
        bufferedOutputStream.close();
        fileOutputStream.close();
        bufferedInputStream.close();
    }

    /**
     * 获取链接中的文件名
     * @param url
     * @return
     */
    public static String getFileName(String url) {
        // 指定文件后缀名称(有需求可以自定义，如doc等等)
        String suffixes="jpeg|jpg|png";
        Pattern pat=Pattern.compile("[\\w]+[\\.]("+suffixes+")");//正则判断
        Matcher mc=pat.matcher(url);//条件匹配
        String fileName = null;
        while(mc.find()) {
            fileName = mc.group();//截取文件名后缀名
        }
        return fileName;
    }
}
